import logging
import math
import csv
import cStringIO
import datetime
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.api import urlfetch
import models, utils, datastore, charts

class CleanAggregates(webapp.RequestHandler):
  def get(self):
    self.post()

  def post(self):
    system = self.request.get('system')
    key = db.Key(system)
    array = models.SolarArray.get(key)   
    aggregate = models.SolarAggregate.all()
    aggregate.filter('system =',array.key())
    l = list(aggregate)
    logging.debug('removing %d records' % len(l))
    db.delete(l)

    self.redirect('/?hours=168&system=' + self.request.get('system'))

class Populate(webapp.RequestHandler):
    def get(self):
      system = self.request.get('system')
      if system != None and system != '':
        key = db.Key(system)
        array = models.SolarArray.get(key)
      else:
        array = models.SolarArray()
        array.owner = 'test data'
        array.tz = 'US/Pacific'
        array.put()
      
      days = int(self.request.get('days','7'))
      m = 2000
      # the amount to increase per minute
      increment = math.pi / (60 * 24)
      minIncrement = 10
      now = datetime.datetime.now()
      then = now - datetime.timedelta(days = days)
      minutes = 0
      kwhToday = 0.0
      kwhIncrement = .25
      kwhLifetime = 0.0
      points = []
      while then < now:
        watts = int(m * math.sin(float(minutes) * increment))
        if watts < 0:
          minutes = 0
          watts = 0
          kwhToday = 0.0
        data = models.SolarData(system = array, watts = watts, date = then, kwhToday = kwhToday, kwhLifetime = kwhLifetime)
        points += [data]
        then = then + datetime.timedelta(minutes = minIncrement)
        minutes += minIncrement
        kwhToday += kwhIncrement
        kwhLifetime += kwhIncrement
      logging.debug('Adding %d points' % len(points))
      db.put(points)
      self.redirect('/?hours=1&system=%s' % array.key())


      
class Clone(webapp.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'text/plain'
    system = self.request.get('system')
    array = models.SolarArray()
    array.owner = 'test data'
    array.tz = 'US/Pacific'
    array.put()
    now = datetime.datetime.now()
    days = int(self.request.get('days','7'))
    for i in xrange(0,days):
      day = now - datetime.timedelta(days = i)
      url = 'http://solar.halem.com/dump?system=%s&day=%d&month=%d&year=%d' % (system,
                                                                               day.day,
                                                                               day.month,
                                                                               day.year)
      logging.debug('Fetching %s' % url)                                                                               
      result = urlfetch.fetch(url)
      if result.status_code == 200:
        reader = csv.reader(cStringIO.StringIO(result.content))
        points = []
        for row in reader:
          date = datetime.datetime.utcfromtimestamp(int(row[0]))
          watts = int(row[1])
          kwhToday = float(row[2])
          kwhLifetime = float(row[3])
          data = models.SolarData(system = array.key(), watts = watts, date = date, kwhToday = kwhToday, kwhLifetime = kwhLifetime)
          points.append(data)
        logging.debug('Saving %d points' % len(points))
        db.put(points)
    self.redirect('/?hours=18&system=%s' % array.key())    


        



        